const charset = require('superagent-charset');
const superagent =  charset(require('superagent'));
require('superagent-proxy')(superagent);
const ProxyAgent = require('proxy-agent');
const HttpsProxyAgent = require("https-proxy-agent");
const cheerio =require('cheerio');

//const got = require('got');

// const {
//     getTaskPage,
//     wxpusher,
// } = require('./ti_scan_config');

const {
    readTask,
} = require('./ti_logic_read_task');

const {
    logger,
    sleep,
    httpGet,
    httpPost,
    getProxy,
    getIp,
    getIp_v5,
    getIp_v6,
    httpProxyGet,
    httpProxyGet2,
    httpProxyGet3,
    httpProxyGet4,
    httpProxyGet6,
    tiGet,
} = require('./util');


const getSessionId = async () => {

    let result = '';
    try{
        result = await httpPost('https://www.turnitin.com/login_page.asp?lang=en_us', {
                email: "turnitin_immlyl77@gmail.com",
                user_password: "ABC12345678",
            }, 'application/x-www-form-urlencoded');
    }catch(e){
        //logger(e);
    }

    //logger(result);

    $ = await cheerio.load(result);

    //logger($.html());

    //logger(11111);

    let session_id = $('input[name=session_id]').val();

    return session_id;

}

//访问首页，找text的链接
const findHome =  async (session_id) => {

    let href_list = [];

    let result = '';
    try{
        result = await httpGet('https://www.turnitin.com/t_home.asp?svr=55&lang=zh_hans&r=36.8181785214929', session_id);
    }catch(e){
        logger(e);
    }

    logger(result);

    $ = await cheerio.load(result);

    //logger($.html());

    //logger(11111);

    //nav__item__footer盘点是有有登陆态

      // <li class="nav__item__footer"><a href="/newuser_type.asp?lang=en_us" class="">Create Account</a></li>|<li
      //               class="nav__item__footer"><a href="/login_page.asp?lang=en_us">Login</a></li>
      //                                               </div>

      //                           <li class="nav__item__footer">
      //                               Change language
      //                             </li>
      let is_login = 1;

      $('.nav__item__footer').each(function(index, item){
            let text = $(this).find('a').text();

            if(text == 'Create Account' || text == 'Login'){
                is_login = 0;
            }
        });



      //重新登录
    if(is_login == 0){
         session_id = await getSessionId();

         logger('session_id', session_id);

         try{
                result = await httpGet('https://www.turnitin.com/t_home.asp?svr=55&lang=zh_hans&r=36.8181785214929', session_id);
            }catch(e){
                logger(e);
            }

            logger(result);

            $ = await cheerio.load(result);
    }


    $('.class_name').each(function(index, item){
        let href = $(this).find('a').attr('href');

        if(href){
            href_list.push(href);
        }

        logger('href=', href );
    });

    //let session_id = $('input[name=session_id]').val();

    return href_list;

}

//访问作业
const findWork =  async (url, session_id) => {

    logger('url', url);

    let result = '';
    try{
        result = await httpGet('https://www.turnitin.com/'+url, session_id);
    }catch(e){
        logger(e);
    }

    //logger(result);

    $ = await cheerio.load(result);

    //logger($.html());

    //logger(11111);

    let href_list = [];

    $('.assgn-inbox').each(function(index, item){
        let href = $(this).find('a').attr('href');

        if(href){
            href_list.push(href);
        }

        logger('href=', href );
    });

    //let session_id = $('input[name=session_id]').val();

    return href_list;

}


const findResult = async (url, session_id) => {

    let result = '';
    try{
        result = await httpGet('https://www.turnitin.com/'+url, session_id);
    }catch(e){
        logger(e);
    }

    //logger(result);

    $ = await cheerio.load(result);

    //logger($.html());

    //logger(11111);
    let con_list = [];

    $('.inbox_table tr').each(function(index, item){
        let tmp = {};
        let author = $(this).find('.ibox_author ').text();

        let title = $(this).find('.ibox_title').find('a').text();

        let percentage = $(this).find('.or-percentage').text();

        let download_href = $(this).find('.dl_file').attr('href');

        //logger('download_href', download_href);

        let download_href_tmp = '';
        
        if(download_href){
            let href_tmp = download_href.split('\'');

            download_href_tmp = href_tmp[1];
        }

        let pid = $(this).find('.pid').text();

        let date = $(this).find('.class_status').text();

        tmp.author = author;

        tmp.title = title;

        tmp.percentage = percentage;

        tmp.download_href = download_href_tmp;

        tmp.pid = pid;

        tmp.date = date;

        con_list.push(tmp);

        //logger('ibox_author=', author );
    });

    logger(con_list);

    //let session_id = $('input[name=session_id]').val();

    return con_list;

}

//获得下载文件链接
const findDownFile =  async (url, session_id) => {

    logger('down_url', 'https://www.turnitin.com'+url);

    let result = '';
    try{
        result = await httpGet('https://www.turnitin.com'+url, session_id);
    }catch(e){
        logger(e);
    }

    //logger(result);

    $ = await cheerio.load(result);

    //logger($.html());

    //logger(11111);

    let href_list = [];

    $('li').each(function(index, item){
        let href = $(this).find('a').attr('href');

        if(href){
            href_list.push(href);
        }

        logger('href=', href );
    });

    //let session_id = $('input[name=session_id]').val();

    return href_list;

}

const findRealDownFile =  async (url, session_id) => {

    let result = '';
    try{
        result = await httpGet('https://www.turnitin.com/'+url, session_id);
    }catch(e){
        logger(e);
    }

    let tmp_url = result.split('\'');

    logger('real_down_file', tmp_url[1]);

    return tmp_url[1];

}


//模拟提交文件

const PostFile =  async (url, aid, session_id) => {

    let result = '';
    //https://www.turnitin.com/t_submit.asp?aid=115262793&session-id=59858b11d23e490fa769b1ae0b39e285&lang=zh_hans
    url = url + '?aid='+aid+'&session-id='+session_id+'&lang=zh_hans';
   
    let data = {
        async_request: 1,
        userID: '',
        author_first: 'li',
        author_last: 'lao',
        title: '文档',
        userfile: '（二进制）',
        db_doc: '',
        dropbox_filename: '',
        google_doc: '',
        google_auth_uri: '',
        token: '',
        submit_button: ''
    }

    try{
        result = await httpPost(url, data);
    }catch(e){
        logger(e);
    }

    logger(result);

    return result;

}

//确认提交文件
//post
//
const ConfirmSub =  async (url, uuid, session_id) => {

    let result = '';
    //https://www.turnitin.com/submit_confirm.asp?lang=zh_hans&session-id=59858b11d23e490fa769b1ae0b39e285&data-state=confirm&uuid=70B31C0A-6A21-11EC-923C-C1A591431812
    
    url = url + '?data-state=confirm&uuid='+uuid+'&session-id='+session_id+'&lang=zh_hans';
   
    try{
        result = await httpPost(url, data);
    }catch(e){
        logger(e);
    }

    logger(result);

    return result;

}


//获得临时结果
//POST
//
const GetSubData =  async (url, session_id) => {

    let result = '';
    //https://www.turnitin.com/panda/get_submission_metadata.asp?session-id=59858b11d23e490fa769b1ae0b39e285&lang=zh_hans&skip_ready_check=0&uuid=70B31C0A-6A21-11EC-923C-C1A591431812
    url = url + '?skip_ready_check=0&uuid='+uuid+'&session-id='+session_id+'&lang=zh_hans';
   
    try{
        result = await httpPost(url, data);
    }catch(e){
        logger(e);
    }

    logger(result);

    return result;

}


let session_id = 'da1e24a249a54f36a19e4ba7727993a6';

(async () => {
    let url = await findHome(session_id);

    let result_url = await findWork(url[0], session_id);

    let result = await findResult(result_url[0], session_id);

    let down_file = await findDownFile(result[1]['download_href'], session_id);

    let real_down_url = await findRealDownFile(down_file[1], session_id);

    let real_result = result[1];

    real_result.real_down_url = 'https://www.turnitin.com' + real_down_url;

    logger(real_result);

    //let session_id = await getSessionId();

    //logger(session_id);
    // try{
    //     let result = await superagent.get('https://www.turnitin.com/');
    // }catch(e){
    //     logger(e);
    // }
    //logger(result);
})();


